package com.xwltz.core.utils;

/**
 * @description VersionTools
 * @information on version 1.0 be created by @xwltz at 2021/11/27 15:34
 */
@SuppressWarnings("unused")
public class VersionUtils {

    /**
     * description: compareVersion
     * 第一个参数大返回正数，第二个参数大返回负数，一样返回0；
     * information: on version 1.0 be created by xwltz at 2021/11/27 15:40
     *
     * @param currentVersion 当前最新版本
     * @param appVersion APP当前版本
     * @return int
     */
    public static int compareVersion(String currentVersion, String appVersion) {
        try {
            if (currentVersion.equals(appVersion)) {
                return 0;
            }
            String[] version1Array = currentVersion.split("\\.");
            String[] version2Array = appVersion.split("\\.");
            int index = 0;
            //获取最小长度值
            int minLen = Math.min(version1Array.length, version2Array.length);
            int diff = 0;
            //循环判断每位的大小
            while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
                index++;
            }
            if (diff == 0) {
                //如果位数不一致，比较多余位数
                for (int i = index; i < version1Array.length; i++) {
                    if (Integer.parseInt(version1Array[i]) > 0) {
                        return 1;
                    }
                }

                for (int i = index; i < version2Array.length; i++) {
                    if (Integer.parseInt(version2Array[i]) > 0) {
                        return -1;
                    }
                }
                return 0;
            } else {
                return diff > 0 ? 1 : -1;
            }
        } catch (Exception ex) {
            return 0;
        }
    }
}
